package com.example.attendance_back.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final String secret = "hand2020";
    private static final Long expiration = 1209600L; // 两天

    public static  String createToken(String username,String sign){

        return JWT.create().withAudience(username)
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))
                .sign(Algorithm.HMAC256(sign));
    }



    public static String generateToken(String username) {

        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + expiration * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                // 添加头部
                .withHeader(map)
                //可以将基本信息放到claims中
                //userName
                .withClaim("userName", username)
                //超时设置,设置过期的日期
                .withExpiresAt(expireDate)
                //签发时间
                .withIssuedAt(new Date())
                //SECRET加密
                .sign(Algorithm.HMAC256(secret));
        return token;

    }


    public static Boolean verifyToken(String token){
        DecodedJWT jwt;

        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        jwt=  verifier.verify(token);

        if(jwt.getExpiresAt().before(new Date())){
            System.out.println("token过期");
            return  false;
        }
        return  true;
    }

}
